<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
   
  <meta name="keywords" content="Java Python" />
   
  <meta name="description" content="From Zero to Hero" />
  
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    JDK1.8源码-00-深拷贝浅拷贝 |  朱酱酱的学习博客
  </title>
  <meta name="generator" content="hexo-theme-yilia-plus">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/css/style.css">

  
<script src="/js/pace.min.js"></script>


  

  

<link rel="alternate" href="/atom.xml" title="朱酱酱的学习博客" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    <main class="content">
      <section class="outer">
  <article id="post-jdk_SourceCode/JDK1.8-00-深拷贝浅拷贝" class="article article-type-post" itemscope
  itemprop="blogPost" data-scroll-reveal>

  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  JDK1.8源码-00-深拷贝浅拷贝
</h1>
  

    </header>
    

    
    <div class="article-meta">
      <a href="/2020/03/25/jdk_SourceCode/JDK1.8-00-%E6%B7%B1%E6%8B%B7%E8%B4%9D%E6%B5%85%E6%8B%B7%E8%B4%9D/" class="article-date">
  <time datetime="2020-03-25T07:52:53.000Z" itemprop="datePublished">2020-03-25</time>
</a>
      
      
      
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">2.6k字</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">10分钟</span>
        </span>
    </span>
</div>

      
    </div>
    

    
    
    <div class="tocbot"></div>





    

    <div class="article-entry" itemprop="articleBody">
      


      

      
      <h1 id="JDK1-8源码-00-深拷贝浅拷贝"><a href="#JDK1-8源码-00-深拷贝浅拷贝" class="headerlink" title="JDK1.8源码-00-深拷贝浅拷贝"></a>JDK1.8源码-00-深拷贝浅拷贝</h1><p>关于Java的深拷贝和浅拷贝，简单来说就是创建一个和一直对象一模一样的对象。</p>
<p>可能日常编码过程中用的不多，但是这是一个面试经常会问的问题，而且了解深拷贝和浅拷贝的原理，对<strong>于Java中的所谓值传递或者引用传递将会有更深的理解。</strong></p>
<a id="more"></a>



<h2 id="1-创建对象的5种方式"><a href="#1-创建对象的5种方式" class="headerlink" title="1. 创建对象的5种方式"></a>1. 创建对象的5种方式</h2><p><strong>①、通过 new 关键字</strong></p>
<p>　　这是最常用的一种方式，通过 new 关键字调用类的有参或无参构造方法来创建对象。比如 Object obj = new Object();</p>
<p><strong>②、通过 Class 类的 newInstance() 方法</strong></p>
<p>这种默认是调用类的<strong>无参构造方法</strong>创建对象。</p>
<p>比如</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Person p = (Person) Class.forName(<span class="string">"com.zhuuu.test.Person"</span>).newInstance();</span><br></pre></td></tr></table></figure>



<p><strong>③、通过 Constructor 类的 newInstance 方法</strong></p>
<p>这和第二种方法类时，都是通过反射来实现。</p>
<p>通过java.lang.reflect.Constructor 类的 newInstance()方法指定某个构造器来创建对象。</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Person p = (Person) Person.class.getConstructors()[0].newInstance();</span><br></pre></td></tr></table></figure>

<p>实际上第二种方法利用 Class 的 newInstance() 方法创建对象，其内部调用还是 Constructor 的 newInstance() 方法。</p>
<p><strong>④、利用 Clone 方法</strong></p>
<p>Clone是Object类中的一个方法，通过对象A.clone()方法会创建一个内容和对象A一模一样的对象B。顾名思义就是创建一个一模一样的对象出来。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Person p4 = (Person) p3.clone();</span><br></pre></td></tr></table></figure>



<p><strong>⑤、反序列化</strong></p>
<p><strong>序列化</strong>是指把<strong>堆内存中的java对象数据</strong>，通过某种方式把对象存储到磁盘文件中或者传递给其他网络节点（在网络上传输）。</p>
<p>而<strong>反序列化</strong>则是把磁盘文件中的对象数据或者把网络节点上的对象数据，恢复成java对象模型的过程。</p>
<h2 id="2-Clone-方法"><a href="#2-Clone-方法" class="headerlink" title="2. Clone() 方法"></a>2. Clone() 方法</h2><p>本篇讲解的是 Java 的深拷贝和浅拷贝，其实现方式正是通过调用 Object 类的 clone() 方法来完成。在 Object.class 类中，源码为：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">native</span> Object <span class="title">clone</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException</span>;</span><br></pre></td></tr></table></figure>

<p>这是一个<strong>用 native 关键字修饰</strong>的方法，关于native关键字,只需要知道用 native 修饰的方法就是告诉操作系统，这个方法我不实现了，让操作系统去实现。</p>
<h2 id="3-基本类型和引用类型"><a href="#3-基本类型和引用类型" class="headerlink" title="3. 基本类型和引用类型"></a>3. 基本类型和引用类型</h2><p>这里再给大家普及一个概念，在 Java 中基本类型和引用类型的区别。</p>
<p><strong>在 Java 中数据类型可以分为两大类：基本类型和引用类型。</strong></p>
<p><strong>基本类型：值类型</strong></p>
<p>①整数类型：<code>long、int、short、byte</code><br>②浮点类型：<code>float、double</code><br>③字符类型：<code>char</code><br>④布尔类型：<code>boolean</code></p>
<p><strong>引用类型：</strong></p>
<ul>
<li><strong>类、 接口类型、 数组类型、 枚举类型、 注解类型、 字符串型</strong></li>
</ul>
<p>例如，<code>String</code>类型就是引用类型。<br><strong>简单来说，所有的非基本数据类型都是引用数据类型。</strong></p>
<p><strong>Java将内存空间分为堆和栈。</strong></p>
<ul>
<li><p><strong>基本类型</strong>直接放在栈中存储数值，</p>
</li>
<li><p><strong>引用类型</strong>是将引用放在栈中。实际存储的值放在堆中，通过栈中的引用指向堆中存放的数据</p>
</li>
</ul>
<p><img src="http://zhuuu-bucket.oss-cn-beijing.aliyuncs.com/img/20200418/215411386.png" alt="mark"></p>
<h2 id="4-浅拷贝"><a href="#4-浅拷贝" class="headerlink" title="4. 浅拷贝"></a>4. 浅拷贝</h2><p>看如下这段代码：</p>
<p>这是我们要进行赋值的原始类Person。下面我们产生一个Person对象，并调用其Clone方法复制一个新的对象。</p>
<p><strong>注意：</strong></p>
<ul>
<li>调用对象的clone方法，必须要让类实现Cloneable接口，</li>
<li>并且覆写clone方法</li>
</ul>
<ol>
<li><strong>Address类</strong></li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Address</span> <span class="keyword">implements</span> <span class="title">Cloneable</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String provices;</span><br><span class="line">    <span class="keyword">private</span> String city;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAddress</span><span class="params">(String provices,String city)</span></span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.provices = provices;</span><br><span class="line">        <span class="keyword">this</span>.city = city;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"Address [provices="</span> + provices + <span class="string">", city="</span> + city + <span class="string">"]"</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li><strong>Person类</strong></li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.zhuuu;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Person</span> <span class="keyword">implements</span> <span class="title">Cloneable</span></span>&#123;</span><br><span class="line">    <span class="comment">// 引用类型</span></span><br><span class="line">    <span class="keyword">public</span> String pname;</span><br><span class="line">    <span class="comment">// 基本类型</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> page;</span><br><span class="line">    <span class="comment">// 引用类型</span></span><br><span class="line">    <span class="keyword">public</span> Address address;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Person</span><span class="params">()</span> </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Person</span><span class="params">(String pname,<span class="keyword">int</span> page)</span></span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.pname = pname;</span><br><span class="line">        <span class="keyword">this</span>.page = page;</span><br><span class="line">        <span class="keyword">this</span>.address = <span class="keyword">new</span> Address();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Object <span class="title">clone</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">super</span>.clone();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAddress</span><span class="params">(String provices,String city )</span></span>&#123;</span><br><span class="line">        address.setAddress(provices, city);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">display</span><span class="params">(String name)</span></span>&#123;</span><br><span class="line">        System.out.println(name+<span class="string">":"</span>+<span class="string">"pname="</span> + pname + <span class="string">", page="</span> + page +<span class="string">","</span>+ address);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getPname</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> pname;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setPname</span><span class="params">(String pname)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.pname = pname;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getPage</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> page;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setPage</span><span class="params">(<span class="keyword">int</span> page)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.page = page;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<ol start="3">
<li>测试类</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.zhuuu;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">testShallowClone</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> CloneNotSupportedException </span>&#123;</span><br><span class="line">        Person p1 = <span class="keyword">new</span> Person(<span class="string">"朱酱酱"</span>, <span class="number">24</span>);</span><br><span class="line">        p1.setAddress(<span class="string">"江苏省"</span>,<span class="string">"南京市"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// p1 的 clone</span></span><br><span class="line">        Person p2 = (Person) p1.clone();</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">"p1"</span> + p1);</span><br><span class="line">        System.out.println(<span class="string">"p1.getPname:"</span>+p1.getPname().hashCode());</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">"p2"</span> + p2);</span><br><span class="line">        System.out.println(<span class="string">"p2.getPname:"</span>+p2.getPname().hashCode());</span><br><span class="line"></span><br><span class="line">        p1.display(<span class="string">"p1"</span>);</span><br><span class="line">        p2.display(<span class="string">"p2"</span>);</span><br><span class="line"></span><br><span class="line">        p2.setAddress(<span class="string">"上海省"</span>,<span class="string">"上海市"</span>);</span><br><span class="line">        System.out.println(<span class="string">"将复制之后的地址修改为："</span>);</span><br><span class="line">        p1.display(<span class="string">"p1"</span>);</span><br><span class="line">        p2.display(<span class="string">"p2"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>测试结果：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">首先看原始类Person实现了Cloneable接口，并且重写了clone方法，</span></span><br><span class="line"><span class="comment">还有它的三个属性，</span></span><br><span class="line"><span class="comment">一个引用类型 String定义的 pname，</span></span><br><span class="line"><span class="comment">一个基本类型 int定义的 page，</span></span><br><span class="line"><span class="comment">还有一个引用类型 Address ，（其中：Address这是一个自定义类，这个类也包含两个属性provices和city</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">接着看测试内容，首先我们创建一个Person对象p1,其pname为朱酱酱，page年龄为24,地址类Address两个属性为江苏省，南京市。接着我们调用clone()方法复制另一个对象p2,接着打印这两个对象的内容。</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line">p1com.zhuuu.Person@<span class="number">4554617</span>c</span><br><span class="line">p1.getPname:<span class="number">26578193</span></span><br><span class="line">p2com.zhuuu.Person@<span class="number">74</span>a14482</span><br><span class="line">p2.getPname:<span class="number">26578193</span></span><br><span class="line">p1:pname=朱酱酱, page=<span class="number">24</span>,Address [provices=江苏省, city=南京市]</span><br><span class="line">p2:pname=朱酱酱, page=<span class="number">24</span>,Address [provices=江苏省, city=南京市]</span><br><span class="line">将复制之后的地址修改为：</span><br><span class="line">p1:pname=朱酱酱, page=<span class="number">24</span>,Address [provices=上海省, city=上海市]</span><br><span class="line">p2:pname=朱酱酱, page=<span class="number">24</span>,Address [provices=上海省, city=上海市]</span><br></pre></td></tr></table></figure>

<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">从第 1 行和第 3 行打印结果:</span><br><span class="line">p1com.zhuuu.Person@4554617c</span><br><span class="line">p2com.zhuuu.Person@74a14482</span><br><span class="line">可以看出这是两个不同的对象。</span><br><span class="line"></span><br><span class="line">从第 5 行和第 6 行打印的对象内容看</span><br><span class="line">p1:pname=朱酱酱, page=24,Address [provices=江苏省, city=南京市]</span><br><span class="line">p2:pname=朱酱酱, page=24,Address [provices=江苏省, city=南京市]</span><br><span class="line">原对象p1和克隆出来的对象p2内容完全相同。</span><br><span class="line"></span><br><span class="line">但是从第 7 行和第 8 行打印结果来看，</span><br><span class="line">代码中我们只是更改了克隆对象 p2 的属性 Address 。</span><br><span class="line">原对象 p1 和克隆对象 p2 的 Address 属性都被修改了。</span><br><span class="line">p1:pname=朱酱酱, page=24,Address [provices=上海省, city=上海市]</span><br><span class="line">p2:pname=朱酱酱, page=24,Address [provices=上海省, city=上海市]</span><br><span class="line"></span><br><span class="line">总结：也就是说对象Person的属性Address，经过<span class="built_in">clone</span>之后，其实只是复制了其引用，他们的指向还是同一块堆内存空间，当修改其中一个对象的属性Address，另一个也会随之变化。</span><br></pre></td></tr></table></figure>



<p><strong>浅拷贝：创建一个新对象，然后将当前对象的非静态字段复制到该新对象，</strong></p>
<ul>
<li><p><strong>如果字段是值类型的，那么对该字段进行赋值。</strong></p>
</li>
<li><p><strong>如果该字段是引用类型的话，则复制引用但不复制引用的对象。</strong></p>
</li>
</ul>
<p><strong>因此，原始对象及其副本引用同一个对象。</strong></p>
<h2 id="5-深拷贝"><a href="#5-深拷贝" class="headerlink" title="5. 深拷贝"></a>5. 深拷贝</h2><p>弄清楚了浅拷贝，那么深拷贝就很容易理解了。</p>
<p><strong>深拷贝：创建一个新对象，然后将当前对象的非静态字段复制到该新对象。无论该字段是值类型还是引用类型，都复制独立的一份。</strong></p>
<p>　那么该如何实现深拷贝呢？<strong>Object 类提供的 clone 是只能实现 浅拷贝的。</strong></p>
<h2 id="6-如何实现深拷贝？"><a href="#6-如何实现深拷贝？" class="headerlink" title="6. 如何实现深拷贝？"></a>6. 如何实现深拷贝？</h2><p>参考博客：<a href="https://www.cnblogs.com/xinruyi/p/11537963.html" target="_blank" rel="noopener">https://www.cnblogs.com/xinruyi/p/11537963.html</a></p>
<p><img src="http://zhuuu-bucket.oss-cn-beijing.aliyuncs.com/img/20200804-102956615.png" alt="mark"></p>
<p>深拷贝的原理我们知道了，就是要让原始对象和克隆之后的对象所具有的引用类型属性不是指向同一块堆内存，这里有两种实现思路。</p>
<p><strong>①、让每个引用类型属性内部都重写clone() 方法</strong></p>
<p>既然引用类型不能实现深拷贝，那么我们将每个引用类型都拆分成基本类型，分别进行浅拷贝。</p>
<p>比如上面的例子，Person 类有一个引用类型 Address(其实String 也是引用类型，但是String类型有点特殊，后面会详细讲解)，</p>
<ol>
<li>我们在Address类内部也重写clone方法。如下：</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.zhuuu;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Address</span> <span class="keyword">implements</span> <span class="title">Cloneable</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String provices;</span><br><span class="line">    <span class="keyword">private</span> String city;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAddress</span><span class="params">(String provices,String city)</span></span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.provices = provices;</span><br><span class="line">        <span class="keyword">this</span>.city = city;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">"Address [provices="</span> + provices + <span class="string">", city="</span> + city + <span class="string">"]"</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 实现深拷贝，让每个引用类型的内部都重写clone方法，拆分成一个一个浅拷贝</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> Object <span class="title">clone</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">super</span>.clone();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="2">
<li>Person.class 的 clone() 方法：</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 拆分成一个一个浅拷贝</span></span><br><span class="line"><span class="comment">// 弊端：Person有一个引用类型Address,Address没有</span></span><br><span class="line"><span class="comment">// 但是，如果Address也有引用类型，那么就要无限重写clone方法下去</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> Object <span class="title">clone</span><span class="params">()</span> <span class="keyword">throws</span> CloneNotSupportedException </span>&#123;</span><br><span class="line">    Person p = (Person) <span class="keyword">super</span>.clone();</span><br><span class="line">    p.address = (Address) address.clone();</span><br><span class="line">    <span class="keyword">return</span> p;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="3">
<li>测试还是和上面一样，我们会发现更改了p2对象的Address属性，p1 对象的 Address 属性并没有变化。</li>
</ol>
<p><strong>这种做法有个弊端，这里如果我们Person类只有一个Address引用类型，而Address类没有，所以我们只用重写Address类的clone方法。</strong></p>
<p><strong>但是如果Address类也存在一个引用类型，那么我们也要重写其Clone方法，这样下去，有多少个引用类型，我们就要重写多少次，如果存在很多引用类型，那么代码量会明显增大。所以这种方式不合适、</strong></p>
<p><strong>②、利用序列化</strong></p>
<p>序列化是将对象写到流中便于传输，</p>
<p>而反序列化则是将对象从流中读取出来，</p>
<p>这里写到流中的对象则是原始对象的一个拷贝，因为原始对象还存在JVM中，所以我们可以利用对象的序列化产生克隆对象，然后通过反序列化获取这个对象。</p>
<p><strong>注意每个需要序列化的类都要实现Serializable接口，如果某个属性不需要序列化，可以将其声明为transient，即将其排除在克隆属性之外。</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.zhuuu;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.io.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Deepclone</span> <span class="keyword">implements</span> <span class="title">Serializable</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">deepclone</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">        <span class="comment">// 序列化</span></span><br><span class="line">        ByteArrayOutputStream bos = <span class="keyword">new</span> ByteArrayOutputStream();</span><br><span class="line">        ObjectOutputStream oos = <span class="keyword">new</span> ObjectOutputStream(bos);</span><br><span class="line"></span><br><span class="line">        oos.writeObject(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 反序列化</span></span><br><span class="line">        ByteArrayInputStream bis = <span class="keyword">new</span> ByteArrayInputStream(bos.toByteArray());</span><br><span class="line">        ObjectInputStream ois = <span class="keyword">new</span> ObjectInputStream(bis);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> ois.readObject();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>注意：因为序列化产生的是两个完全独立的对象，所以无论嵌套多少个引用类型，序列化都是能实现深拷贝的。</p>

      
      <!-- reward -->
      
      <div id="reward-btn">
        打赏
      </div>
      
    </div>
      <!-- copyright -->
      
        <div class="declare">
          <ul class="post-copyright">
            <li>
              <i class="ri-copyright-line"></i>
              <strong>版权声明： </strong s>
              本博客所有文章除特别声明外，均采用 <a href="https://www.apache.org/licenses/LICENSE-2.0.html" rel="external nofollow"
                target="_blank">Apache License 2.0</a> 许可协议。转载请注明出处！
            </li>
          </ul>
        </div>
        
    <footer class="article-footer">
      
          
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="//api.qrserver.com/v1/create-qr-code/?size=150x150&data=http://zhuuu.work/2020/03/25/jdk_SourceCode/JDK1.8-00-%E6%B7%B1%E6%8B%B7%E8%B4%9D%E6%B5%85%E6%8B%B7%E8%B4%9D/" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JDK%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/" rel="tag">JDK源码分析</a></li></ul>


    </footer>

  </div>

  
  
  <nav class="article-nav">
    
      <a href="/2020/03/26/SpringBoot/SpringBoot-05-%E8%87%AA%E5%8A%A8%E9%85%8D%E7%BD%AE%E5%8E%9F%E7%90%86/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            SpringBoot-05-自动配置原理
          
        </div>
      </a>
    
    
      <a href="/2020/03/25/SpringBoot/SpringBoot-04-JSR303%E6%A0%A1%E9%AA%8C%E5%92%8C%E5%A4%9A%E7%8E%AF%E5%A2%83%E5%88%87%E6%8D%A2/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">SpringBoot-04-JSR303校验和多环境切换</div>
      </a>
    
  </nav>


  

  
  
<!-- valine评论 -->
<div id="vcomments-box">
    <div id="vcomments">
    </div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='https://cdn.jsdelivr.net/npm/valine@1.3.10/dist/Valine.min.js'></script>
<script>
    new Valine({
        el: '#vcomments',
        notify: false,
        verify: '',
        app_id: '',
        app_key: '',
        path: window.location.pathname,
        avatar: 'mp',
        placeholder: '给我的文章加点评论吧~',
        recordIP: true
    });
    const infoEle = document.querySelector('#vcomments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
        infoEle.childNodes.forEach(function (item) {
            item.parentNode.removeChild(item);
        });
    }
</script>
<style>
    #vcomments-box {
        padding: 5px 30px;
    }

    @media screen and (max-width: 800px) {
        #vcomments-box {
            padding: 5px 0px;
        }
    }

    #vcomments-box #vcomments {
        background-color: #fff;
    }

    .v .vlist .vcard .vh {
        padding-right: 20px;
    }

    .v .vlist .vcard {
        padding-left: 10px;
    }
</style>

  

  
  
<div class="gitalk" id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1.5.0/dist/gitalk.css">


<script src="https://cdn.jsdelivr.net/npm/gitalk@1.5.0/dist/gitalk.min.js"></script>


<script src="https://cdn.jsdelivr.net/npm/blueimp-md5@2.10.0/js/md5.min.js"></script>

<script type="text/javascript">
  var gitalk = new Gitalk({
    clientID: 'db188ed8c86dc4b0dbf3',
    clientSecret: 'a58f92160e5a9efd726b7d533000a0737f3e3f3e',
    repo: 'Blog-comments',
    owner: 'Zhuuuuuuuu',
    admin: ['Zhuuuuuuuu'],
    // id: location.pathname,      // Ensure uniqueness and length less than 50
    id: md5(location.pathname),
    distractionFreeMode: false,  // Facebook-like distraction free mode
    pagerDirection: 'last'
  })

  gitalk.render('gitalk-container')
</script>

  

</article>
</section>
      <footer class="footer">
  <div class="outer">
    <ul class="list-inline">
      <li>
        &copy;
        2019-2021
        Zhuuu
      </li>
      <li>
        
      </li>
    </ul>
    <ul class="list-inline">
      <li>
        
        
        <span>
  <i>PV:<span id="busuanzi_value_page_pv"></span></i>
  <i>UV:<span id="busuanzi_value_site_uv"></span></i>
</span>
        
      </li>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
    <div class="to_top">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>
      </div>
    </main>
      <aside class="sidebar">
        <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="朱酱酱的学习博客"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/JVM/">JVM</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/JDK%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/">JDK源码</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/">多线程</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/Mysql/">Mysql</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/Redis/">Redis</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E8%AE%BE%E8%AE%A1%E8%80%85%E6%A8%A1%E5%BC%8F/">设计模式</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/MyBatis/">MyBatis</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/SpringMVC/">SpringMVC</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/Spring/">Spring</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/SpringBoot/">SpringBoot</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">Linux</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/Leetcode/">Leetcode</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E5%89%8D%E7%AB%AF/">前端</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/">网络编程</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags/photoshop/">photoshop</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="http://smartzhuuu.lofter.com/" target="_blank" rel="noopener">摄影</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/2020/about">关于我</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
      </aside>
      <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
      
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/jquery.justifiedGallery.min.js"></script>


<script src="/js/lazyload.min.js"></script>


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<script src="/js/share.js"></script>



<script src="/fancybox/jquery.fancybox.min.js"></script>




<script>
  try {
    var typed = new Typed("#subtitle", {
    strings: ['昨夜西风凋碧树。独上高楼，望尽天涯路','衣带渐宽终不悔，为伊消得人憔悴。','众里寻他千百度。蓦然回首，那人却在，灯火阑珊处。'],
    startDelay: 0,
    typeSpeed: 200,
    loop: true,
    backSpeed: 100,
    showCursor: true
    });
  } catch (err) {
  }
  
</script>




<script src="/js/tocbot.min.js"></script>

<script>
  // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer:'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto',
    onClick: (e) => {
      $('.toc-link').removeClass('is-active-link');
      $(`a[href=${e.target.hash}]`).addClass('is-active-link');
      $(e.target.hash).scrollIntoView();
      return false;
    }
  });
</script>


<script>
  var ayerConfig = {
    mathjax: true
  }
</script>


<script src="/js/ayer.js"></script>


<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>



<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
  });

  MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for(i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.6/unpacked/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>


<script type="text/javascript" src="https://js.users.51.la/20544303.js"></script>
  </div>
</body>

</html>